package wetalk.software.bupt.com.wetalk.application;

import android.app.Application;
import android.app.NotificationManager;
import android.media.MediaPlayer;

import java.util.HashMap;
import java.util.Map;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.util.CollectionUtils;
import wetalk.software.bupt.com.wetalk.util.SharePreferenceUtil;

/**
 * Created by zhangjie on 2017/11/28.
 */

public class CustomApplication extends Application{
    public static CustomApplication mInstance;
    private Map<String, ChatUser> contactList = new HashMap<String, ChatUser>();
    private NotificationManager mNotificationManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        init();
    }

    public static CustomApplication getInstance() {
        return mInstance;
    }

    private void init() {
        mMediaPlayer = MediaPlayer.create(this, R.raw.beep);
        mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        // 若用户登陆过，则先从好友数据库中取出好友list存入内存中
        if (UserManager.getInstance(getApplicationContext())
                .getCurrentUser() != null) {
            // 获取本地好友user list到内存,方便以后获取好友list
            contactList = CollectionUtils.list2map(WeTalkDB.create(getApplicationContext()).getContactList());
        }
    }

    // 单例模式，才能及时返回数据
    SharePreferenceUtil mSpUtil;
    public static final String PREFERENCE_NAME = "_sharedinfo";

    public synchronized SharePreferenceUtil getSpUtil() {
        if (mSpUtil == null) {
            String currentId = UserManager.getInstance(
                    getApplicationContext()).getCurrentUserObjectId();
            String sharedName = currentId + PREFERENCE_NAME;
            mSpUtil = new SharePreferenceUtil(this, sharedName);
        }
        return mSpUtil;
    }

    MediaPlayer mMediaPlayer;

    public synchronized MediaPlayer getMediaPlayer() {
        if (mMediaPlayer == null)
            mMediaPlayer = MediaPlayer.create(this, R.raw.beep);
        return mMediaPlayer;
    }

    /**
     * 设置好友user list到内存中
     * @param contactList
     */
    public void setContactList(Map<String, ChatUser> contactList) {
        if (this.contactList != null) {
            this.contactList.clear();
        }
        this.contactList = contactList;
    }

    /**
     * 退出登录,清空缓存数据
     */
    public void logout() {
        UserManager.getInstance(getApplicationContext()).logout();
        setContactList(null);
    }
}
